<template>
  <div class="rich-viewer">
    <Editor
      style="height: 400px; overflow-y: auto;"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, ref, shallowRef, watch } from 'vue'
import { Editor } from '@wangeditor/editor-for-vue'

interface Props {
  value?: string
}

const props = withDefaults(defineProps<Props>(), {
  value: ''
})

const editorRef = shallowRef()
const mode = 'default'

const valueHtml = ref('')

watch(
  () => props.value,
  (newVal) => {
    valueHtml.value = newVal
  },
  { immediate: true }
)

const editorConfig = {
  placeholder: '',
  readOnly: true,
  scroll: true
}

const handleCreated = (editor: any) => {
  editorRef.value = editor
  console.log('viewer created', editor)
}

onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
</script>

<style scoped>
.rich-viewer {
  border: 1px solid #ccc;
  border-radius: 4px;
}

.rich-viewer :deep(.w-e-text-container) {
  background-color: #f9f9f9;
}

.rich-viewer :deep(.w-e-text-placeholder) {
  display: none;
}
</style>
